<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref, watch } from 'vue';
import { useAuthStore } from '@/store/modules/auth';

interface Props {
  visible?: boolean;
  url?: string;
  title?: string;
  width?: number | string;
  height?: number | string;
  closable?: boolean;
  maskClosable?: boolean;
}

interface Emits {
  (e: 'update:visible', visible: boolean): void;
  (e: 'success', data?: any): void;
  (e: 'close', hasChanges?: boolean): void;
  (e: 'error', error?: any): void;
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  url: '',
  title: '库存助手',
  width: '85%',
  height: '85%',
  closable: true,
  maskClosable: true
});

const emit = defineEmits<Emits>();

const authStore = useAuthStore();

// 响应式状态
const loading = ref(false);
const hasChanges = ref(false);
const iframeRef = ref<HTMLIFrameElement>();

// 计算实际URL
const actualUrl = computed(() => {
  if (!props.url) return '';

  const user = authStore.userInfo;
  // 库存助手用户数据中可能包含objectId字段，或者使用userId
  const userId = (user as any)?.objectId || user?.userId;

  // 调试信息
  console.log('H5Router URL构建:', {
    url: props.url,
    user,
    userId,
    baseUrl: import.meta.env.VITE_H5_BASE_URL
  });

  if (!userId) {
    console.warn('H5Router: 未找到用户ID，使用原始URL');
    return props.url;
  }

  const baseUrl = import.meta.env.VITE_H5_BASE_URL || 'https://web.jimuzhou.top';
  // 🔧 修复：不使用encodeURIComponent，直接拼接URL，与原组件保持一致
  const routerUrl = `${baseUrl}/pages/commonNew/h5Router?uid=${userId}&url=${props.url}?timestamp=${Date.now()}`;

  console.log('H5Router最终URL(修复后):', routerUrl);
  return routerUrl;
});

// 响应式尺寸计算
const windowSize = ref({
  width: window.innerWidth,
  height: window.innerHeight
});

const containerStyle = computed(() => {
  const { width, height } = windowSize.value;

  let containerWidth: number;
  let containerHeight: number;

  if (typeof props.width === 'string' && props.width.includes('%')) {
    containerWidth = Math.min(width * (Number.parseFloat(props.width) / 100), 1200);
  } else {
    containerWidth = Math.min(Number(props.width) || width * 0.85, 1200);
  }

  if (typeof props.height === 'string' && props.height.includes('%')) {
    containerHeight = Math.min(height * (Number.parseFloat(props.height) / 100), 800);
  } else {
    containerHeight = Math.min(Number(props.height) || height * 0.85, 800);
  }

  return {
    width: `${containerWidth}px`,
    height: `${containerHeight}px`
  };
});

const iframeStyle = computed(() => {
  const container = containerStyle.value;
  return {
    width: container.width,
    height: `calc(${container.height} - 60px)` // 减去头部高度
  };
});

// 事件处理
const handleMaskClick = () => {
  if (props.maskClosable) {
    handleClose();
  }
};

const handleClose = () => {
  emit('update:visible', false);
  emit('close', hasChanges.value);
  hasChanges.value = false;
};

const handleIframeLoad = () => {
  console.log('H5Router iframe加载成功');
  loading.value = false;
};

const handleIframeError = (error: Event) => {
  console.error('H5Router iframe加载失败:', error);
  loading.value = false;
  window.$message?.error('页面加载失败，请检查网络连接或URL是否正确');
  emit('error', error);
};

// 监听iframe消息
const handleMessage = (event: MessageEvent) => {
  if (!iframeRef.value) return;

  // 安全检查：验证消息来源
  const allowedOrigins = ['https://web.jimuzhou.top', 'http://localhost:8080'];

  if (!allowedOrigins.includes(event.origin)) {
    return;
  }

  const { data } = event;

  // 处理操作成功消息
  if (data === 'editSuccess' || data === 'saveSuccess' || data === 'addSuccess') {
    hasChanges.value = true;
    emit('success', data);

    // 自动关闭弹窗
    setTimeout(() => {
      handleClose();
    }, 1000);
  }

  // 处理关闭消息
  if (data === 'closeModal' || data === 'close') {
    handleClose();
  }
};

// 窗口尺寸监听
const handleResize = () => {
  windowSize.value = {
    width: window.innerWidth,
    height: window.innerHeight
  };
};

// 监听visible变化，开始加载
watch(
  () => props.visible,
  newVisible => {
    if (newVisible && props.url) {
      loading.value = true;
      hasChanges.value = false;

      // 设置15秒超时，防止一直加载
      setTimeout(() => {
        if (loading.value) {
          loading.value = false;
          window.$message?.error('页面加载超时，请检查网络连接');
        }
      }, 15000);
    }
  }
);

// 监听URL变化
watch(
  () => props.url,
  () => {
    if (props.visible && props.url) {
      loading.value = true;
    }
  }
);

// 生命周期
onMounted(() => {
  window.addEventListener('message', handleMessage);
  window.addEventListener('resize', handleResize);
});

onUnmounted(() => {
  window.removeEventListener('message', handleMessage);
  window.removeEventListener('resize', handleResize);
});
</script>

<template>
  <Teleport to="body">
    <div v-if="visible" class="h5-router-mask" @click="handleMaskClick">
      <div class="h5-router-container" :style="containerStyle" @click.stop>
        <div class="h5-router-header">
          <h3 class="h5-router-title">{{ title }}</h3>
          <button class="h5-router-close" :disabled="loading" @click="handleClose">
            <SvgIcon icon="ant-design:close-outlined" class="h-16px w-16px" />
          </button>
        </div>

        <div v-if="loading" class="h5-router-loading">
          <SvgIcon icon="ant-design:loading-outlined" class="h-20px w-20px animate-spin" />
          <span class="ml-8px">加载中...</span>
        </div>

        <iframe
          v-else
          ref="iframeRef"
          :src="actualUrl"
          class="h5-router-iframe"
          :style="iframeStyle"
          @load="handleIframeLoad"
          @error="handleIframeError"
        />
      </div>
    </div>
  </Teleport>
</template>

<style scoped>
.h5-router-mask {
  @apply fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-9999;
  backdrop-filter: blur(4px);
  animation: fadeIn 0.3s ease-out;
}

.h5-router-container {
  @apply bg-white rounded-12px shadow-2xl overflow-hidden flex flex-col;
  animation: slideIn 0.3s ease-out;
}

.h5-router-header {
  @apply flex items-center justify-between p-16px bg-gray-50 border-b border-gray-200 min-h-60px;
}

.h5-router-title {
  @apply text-16px font-600 text-gray-900 m-0;
}

.h5-router-close {
  @apply w-32px h-32px rounded-8px bg-transparent border-none cursor-pointer flex items-center justify-center text-gray-500 transition-all duration-200;
}

.h5-router-close:hover:not(:disabled) {
  @apply bg-gray-200 text-gray-900 scale-105;
}

.h5-router-close:disabled {
  @apply cursor-not-allowed opacity-50;
}

.h5-router-loading {
  @apply flex items-center justify-center p-32px text-gray-600 text-14px;
}

.h5-router-iframe {
  @apply border-none w-full flex-1 bg-white;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: scale(0.95) translateY(-20px);
  }
  to {
    opacity: 1;
    transform: scale(1) translateY(0);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .h5-router-container {
    @apply m-20px max-w-[calc(100vw-40px)] max-h-[calc(100vh-40px)] rounded-8px;
  }

  .h5-router-header {
    @apply p-12px min-h-50px;
  }

  .h5-router-title {
    @apply text-14px;
  }

  .h5-router-close {
    @apply w-28px h-28px;
  }
}

@media (max-width: 480px) {
  .h5-router-container {
    @apply m-10px max-w-[calc(100vw-20px)] max-h-[calc(100vh-20px)] rounded-6px;
  }
}
</style>
